﻿using UnityEngine;
using Unity.Jobs;
using Unity.Entities;
using Unity.Collections;
using Unity.Transforms;
using Unity.Burst;

// [DisableAutoCreation]
public class TestSystem : JobComponentSystem
{
    EntityQuery entityQuery;
    protected override void OnCreate()
    {
        entityQuery = this.GetEntityQuery(typeof(Translation), typeof(TestComponent));
    }
    [BurstCompile]
    struct TestJob:IJobChunk
    {
        [ReadOnly]
        public float deltaTime;
        [ReadOnly]
        public int minHeight;
        [ReadOnly]
        public int velocity;
        [ReadOnly]
        public float delay;
        public ComponentTypeHandle<Translation> archetypeTranslation;
        public ComponentTypeHandle<TestComponent> archetypeTest;
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            var tranArray = chunk.GetNativeArray<Translation>(archetypeTranslation);
            var testArray = chunk.GetNativeArray<TestComponent>(archetypeTest);
            for(int i=0; i<chunk.Count; i++)
            {
                var testData = testArray[i];
                var translation = tranArray[i];
                if(testData.delayTime > 0)
                {
                    testData.delayTime -= deltaTime;
                }
                else
                {
                    if(translation.Value.y < minHeight)
                    {
                        translation.Value.y = 0;
                        testData.velocity = velocity;
                        testData.delayTime = delay;
                    }
                    else
                    {
                        translation.Value.y -= testData.velocity * deltaTime;
                    }
                }
                testArray[i] = testData;
                tranArray[i] = translation;
            }
        }
    }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var tranArchetype = this.GetComponentTypeHandle<Translation>();
        var testArchetype = this.GetComponentTypeHandle<TestComponent>();
        TestJob testJob = new TestJob
        {
            deltaTime = Time.DeltaTime,
            minHeight = -40,
            archetypeTranslation = tranArchetype,
            archetypeTest = testArchetype,
            delay = UnityEngine.Random.Range(1, 10),
            velocity = UnityEngine.Random.Range(1, 10),
        };
        JobHandle outputDeps = testJob.Schedule(entityQuery, inputDeps);
        return outputDeps;
    }
}
